package trading.algo;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import trading.bo.EmailAccessorBO;
import trading.bo.IBAccessorBO;
import trading.util.OrderSplitHelper;

public class STKShortSellingTask extends TimerTask {

    private String ticker;
    private int size;
    private IBAccessorBO ibAccessorBO;
    private EmailAccessorBO emailAccessorBO;
    private OrderSplitHelper orderSplitHelper;
    private boolean shouldSplitOrder;

    public STKShortSellingTask(String ticker, int size,
            IBAccessorBO ibAccessorBO, EmailAccessorBO emailAccessorBO,
            OrderSplitHelper orderSplitHelper, boolean shouldSplitOrder) {
        this.ticker = ticker;
        this.size = size;
        this.ibAccessorBO = ibAccessorBO;
        this.emailAccessorBO = emailAccessorBO;
        this.orderSplitHelper = orderSplitHelper;
        this.shouldSplitOrder = shouldSplitOrder;
    }

    @Override
    public void run() {

        if (this.shouldSplitOrder) {
            List<Integer> splitSizes = this.orderSplitHelper
                    .splitStkShortSellingOrder(this.size);
            Timer timer = new Timer();
            double taskID = 0;
            for (Integer orderSize : splitSizes) {
                STKShortSellingTask stkShortSellingTask = new STKShortSellingTask(
                        ticker, orderSize, ibAccessorBO, emailAccessorBO,
                        orderSplitHelper, false);
                timer.schedule(stkShortSellingTask, (long) (taskID * 1000));
                taskID += 0.25;
            }
            TimerKillerTask timerKillerTask = new TimerKillerTask(timer);
            timer.schedule(timerKillerTask, (long) (taskID * 1000));
        } else {
            this.ibAccessorBO.createShortSellingOrder(ticker, size);
            this.emailAccessorBO.sendNewShortStockOrderEmail(ticker, size + "");
        }
    }

    public static int secondsNeeded() {
        return 20;
    }

}
